package io.github.consoles.dsa;

import java.util.Iterator;

/**
 * Created by yiihua-013 on 17/3/31.
 * <p>
 * 双端队列
 */
public class LinkedDequeue<Item> implements Iterable<Item> {

    private class Node{

        Item item;
        Node prev;
        Node next;

        Node(Item item){
            this.item = item;
        }
    }

    private Node first,last;
    private int size;

    public boolean isEmpty() {
        return size == 0;
    }

    public int size() {
        return size;
    }

    public void pushLeft(Item item) {
        if (isEmpty()) pushRight(item);
        else {
            Node node = new Node(item);
            node.next = first;
            first.prev = node;
            first = node;
            size++;
        }
    }

    public void pushRight(Item item) {

        Node node = new Node(item);
        if (first == null) first = last = node;
        else {
            node.prev = last;
            last.next = node;
            last = node;
        }
        size++;
    }

    public Item popLeft() {
        if (isEmpty()) return null;

        size--;
        Node node = first;
        first = first.next;
        node.next = null;
        first.prev = null;
        return node.item;
    }

    public Item popRight() {
        if (isEmpty()) return null;

        size--;
        Node node = last;
        last = last.prev;
        last.next = null;
        node.prev = null;
        return node.item;
    }

    private class DequeueIterator implements Iterator<Item> {

        Node current = first;

        @Override
        public boolean hasNext() {
            return current != null;
        }

        @Override
        public Item next() {
            Item item = current.item;
            current = current.next;
            return item;
        }
    }

    @Override
    public Iterator<Item> iterator() {
        return new DequeueIterator();
    }
}
